﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;
using System.Collections;

namespace Profari_Heldur_Utan_Um_Prof
{
    public partial class EditCheckboxes : Form
    {
        #region SQL connection
        private static SqlConnection con = new SqlConnection("Data Source=orninn.com;Initial Catalog=Notendaprofanir;Persist Security Info=True;User ID=SonjaNew;Password=Léttjógúrt ");
        private static DataTable dt = new DataTable();
        private static DataSet ds = new DataSet();
        SqlDataReader r = null;
        #endregion

        #region Variables
        int globalGroupsID;
        int globalEvaluationID;
        ArrayList taskIDs;
        public static ArrayList newTaskIds = new ArrayList();
        #endregion

        #region static variables
        static public int chkIntroSessionValue;
        static public int chkInfoUserBeforeValue;
        static public int chkNameValue;
        static public int chkSsnValue;
        static public int chkMobileValue;
        static public int chkAddressValue;
        static public int chkGenderValue;
        static public int chkBirthYearValue;
        static public int chkOtherValue;
        static public int chkInfoUserAfterValue;
        static public int chkRadQuestions;
        static public int radEssayValue = 0;
        static public int radSurveyValue = 0;
        static public string txtEmailValue;
        static public int chkEmailValue;
        static public int chkUserFeedback;
        #endregion

        public EditCheckboxes()
        {
            this.StartPosition = FormStartPosition.CenterScreen;
            taskIDs = EditTask.TaskID;
            globalGroupsID = EditTask.globalGroupsID;
            globalEvaluationID = EditTask.globalEvaluationID;
            InitializeComponent();
        }

        public EditCheckboxes(int groupID, int evaluationID, ArrayList taskID)
        {
            taskIDs = taskID;
            globalGroupsID = groupID;
            globalEvaluationID = evaluationID;
            InitializeComponent();
        }

        private void EditCheckboxes_Load(object sender, EventArgs e)
        {

            getCheckBoxInfo();
            chkEmail.Checked = false;
            txtEmail.Enabled = false;
        }

        private void chkInfoUserAfter_CheckedChanged(object sender, EventArgs e)
        {
            if (chkInfoUserAfter.CheckState == CheckState.Checked)
            {
                radEssay.Enabled = true;
                radSurvey.Enabled = true;
            }
            else
            {
                if (chkIntroEvaluation.CheckState == CheckState.Checked)
                {
                    btnFinish.Hide();
                    btnNext.Show();
                }
                else
                {
                    btnFinish.Show();
                    btnNext.Hide();
                }

                radEssay.Enabled = false;
                radSurvey.Enabled = false;
            }
        }

        public void getCheckBoxes()
        {
            chkIntroSessionValue = chkIntroEvaluation.CheckState.GetHashCode();
            chkInfoUserBeforeValue = chkInfoUserBefore.CheckState.GetHashCode();
            chkNameValue = chkName.CheckState.GetHashCode();
            chkSsnValue = chkSsn.CheckState.GetHashCode();
            chkMobileValue = chkMobile.CheckState.GetHashCode();
            chkAddressValue = chkAddress.CheckState.GetHashCode();
            chkGenderValue = chkGender.CheckState.GetHashCode();
            chkBirthYearValue = chkBirthYear.CheckState.GetHashCode();
            chkOtherValue = chkOther.CheckState.GetHashCode();
            chkInfoUserAfterValue = chkInfoUserAfter.CheckState.GetHashCode();
            if (radEssay.Checked == true)
            {
                radEssayValue = 1;
                radSurveyValue = 0;
            }
            if (radSurvey.Checked == true)
            {
                radSurveyValue = 1;
                radEssayValue = 0;
            }
            txtEmailValue = txtEmail.Text;
            chkEmailValue = chkEmail.CheckState.GetHashCode();
        }

        #region Buttons
        private void btnCancel_Click(object sender, EventArgs e)
        {
            //If cancel button is pressed user get's a question if he wants to quit making a project or not
            DialogResult cancelProject = MessageBox.Show("Are you sure you want to stop editing?", "Quit", MessageBoxButtons.YesNo);
            if (cancelProject == DialogResult.Yes)
            {
                System.Threading.Thread testerInterface = new System.Threading.Thread(new System.Threading.ThreadStart(OpenTesterInterface));
                testerInterface.SetApartmentState(System.Threading.ApartmentState.STA);
                testerInterface.Start();
                EditTask.taskList.Clear();
                EditTask.TaskID.Clear();
                EditTask.newTaskIds.Clear();
                this.Close();
            }
        }

        private void btnBack_Click(object sender, EventArgs e)
        {
            System.Threading.Thread editTask = new System.Threading.Thread(new System.Threading.ThreadStart(OpenEditTask));
            editTask.SetApartmentState(System.Threading.ApartmentState.STA);
            editTask.Start();
            EditTask.TaskID.Clear();
            this.Close();
        }

        private void btnNext_Click(object sender, EventArgs e)
        {
            if (chkIntroEvaluation.Checked)
            {
                getCheckBoxes();
                System.Threading.Thread editIntroductionText = new System.Threading.Thread(new System.Threading.ThreadStart(OpenEditInroductionText));
                editIntroductionText.SetApartmentState(System.Threading.ApartmentState.STA);
                editIntroductionText.Start();
                this.Close(); ;
            }
        }

        private void btnFinish_Click(object sender, EventArgs e)
        {
            DialogResult finish = MessageBox.Show("Are you sure you wan to update these optios? Changes will be saved", "Update", MessageBoxButtons.YesNo);
            if (finish == DialogResult.Yes)
            {
                updateGroupName();
                updateEvaluationName();
                updateUrl();

                updateTasks();
                insertTasks();
                getNewTaskIds();
                insertEvaluationTask();
                updateCheckBoxInfo();
                System.Threading.Thread listOfProjects = new System.Threading.Thread(new System.Threading.ThreadStart(OpenListOfProjects));
                listOfProjects.SetApartmentState(System.Threading.ApartmentState.STA);
                listOfProjects.Start();
                EditTask.taskList.Clear();
                EditTask.TaskID.Clear();
                EditTask.newTaskIds.Clear();
                this.Close();
            }
        }
        #endregion

        #region Sql Commands
        private void updateGroupName()
        {
            try
            {
                con.Open();
                SqlCommand cmd = new SqlCommand("UPDATE Groups SET name='" + EditTask.groupName + "' WHERE id='" + globalGroupsID + "'", con);
                cmd.ExecuteNonQuery();

            }
            catch (SqlException ex)
            {
                Console.WriteLine("Error: {0}", ex.ToString());

            }
            finally
            {
                if (con != null)
                {
                    con.Close();
                }
            }
        }

        private void updateEvaluationName()
        {
            try
            {
                con.Open();
                SqlCommand cmd = new SqlCommand("UPDATE Evaluation SET name='" + EditTask.evaluationName + "' where ID='" + globalEvaluationID + "'", con);
                cmd.ExecuteNonQuery();
            }
            catch (SqlException ex)
            {
                Console.WriteLine("Error: {0}", ex.ToString());

            }
            finally
            {
                if (con != null)
                {
                    con.Close();
                }
            }
        }

        private void updateUrl()
        {
            try
            {
                con.Open();
                SqlCommand cmd = new SqlCommand("UPDATE Evaluation SET url='" + EditTask.webPageUrl + "' WHERE id='" + globalEvaluationID + "'", con);
                cmd.ExecuteNonQuery();
            }
            catch (SqlException ex)
            {
                Console.WriteLine("Error: {0}", ex.ToString());

            }
            finally
            {
                if (con != null)
                {
                    con.Close();
                }
            }
        }

        private void insertTasks()
        {
            foreach (EditTask.Tasks TaskObj in EditTask.taskList)
            {
                try
                {
                    con.Open();
                    SqlCommand cmd = new SqlCommand("INSERT INTO Task(name, taskDescription, scenariosDescription) VALUES(@txtname, @txtTaskDescript, @txtScenario)", con);
                    cmd.Parameters.AddWithValue("@txtname", (TaskObj.task == "" ? DBNull.Value : (object)TaskObj.task));
                    cmd.Parameters.AddWithValue("@txtTaskDescript", (TaskObj.taskDescript == "" ? DBNull.Value : (object)TaskObj.taskDescript));
                    cmd.Parameters.AddWithValue("@txtScenario", (TaskObj.scenarioTask == "" ? DBNull.Value : (object)TaskObj.scenarioTask));
                    cmd.ExecuteNonQuery();
                }
                catch (SqlException ex)
                {
                    Console.WriteLine("Error: {0}", ex.ToString());
                }
                finally
                {
                    if (con != null)
                    {
                        con.Close();
                    }
                }
            }
        }

        private void getNewTaskIds()
        {
            try
            {
                con.Open();
                SqlCommand cmd = new SqlCommand("SELECT TOP " + EditTask.taskList.Count + " id FROM Task ORDER BY ID desc", con);
                r = cmd.ExecuteReader();
                while (r.Read())
                {
                    if (!r.IsDBNull(0))
                    {
                        newTaskIds.Add(r.GetInt32(0));
                    }
                }
            }
            catch (SqlException ex)
            {
                Console.WriteLine("Error: {0}", ex.ToString());

            }
            finally
            {
                if (con != null)
                {
                    con.Close();
                }
            }
        }

        private void updateTasks()
        {
            int id = 0;
            List<EditTask.Tasks> temp = new List<EditTask.Tasks>(EditTask.taskList);
            foreach (EditTask.Tasks TaskObj in EditTask.taskList)
            {
                if (id == EditTask.TaskID.Count)
                    break;
                try
                {
                    con.Open();
                    SqlCommand cmd = new SqlCommand("Update Task set name=@txtname, taskDescription=@txtTaskDescript, scenariosDescription=@txtScenario WHERE id=" + taskIDs[id], con);
                    cmd.Parameters.AddWithValue("@txtname", (TaskObj.task == "" ? DBNull.Value : (object)TaskObj.task));
                    cmd.Parameters.AddWithValue("@txtTaskDescript", (TaskObj.taskDescript == "" ? DBNull.Value : (object)TaskObj.taskDescript));
                    cmd.Parameters.AddWithValue("@txtScenario", (TaskObj.scenarioTask == "" ? DBNull.Value : (object)TaskObj.scenarioTask));
                    cmd.ExecuteNonQuery();
                    temp.Remove(TaskObj);
                }
                catch (SqlException ex)
                {
                    Console.WriteLine("Error: {0}", ex.ToString());
                }
                finally
                {
                    if (con != null)
                    {
                        con.Close();
                    }
                }
                id++;
                EditTask.taskList = temp;
            }
        }

        private void insertEvaluationTask()
        {
            foreach (int id in newTaskIds)
            {
                try
                {
                    con.Open();
                    SqlCommand cmd = new SqlCommand("INSERT INTO EvaluationTask(evaluationID, taskID, introBeforeEvaluationID) values(@evaluationID, @taskID, @introBFEvalID)", con);
                    cmd.Parameters.AddWithValue("@evaluationID", globalEvaluationID == 0 ? DBNull.Value : (object)globalEvaluationID);
                    cmd.Parameters.AddWithValue("@taskID", id == 0 ? DBNull.Value : (object)id);
                    cmd.Parameters.AddWithValue("@introBFEvalID", DBNull.Value);
                    cmd.ExecuteNonQuery();

                }
                catch (SqlException ex)
                {
                    Console.WriteLine("Error: {0}", ex.ToString());

                }
                finally
                {
                    if (con != null)
                    {
                        con.Close();
                    }
                }
            }
        }

        private void getGroupID()
        {
            try
            {
                con.Open();
                SqlCommand cmd = new SqlCommand("SELECT id FROM Groups WHERE name='" + EditTask.selectedExistingGroup + "'", con);
                r = cmd.ExecuteReader();
                while (r.Read())
                {
                    globalGroupsID = r.GetInt32(0);
                }
            }
            catch (SqlException ex)
            {
                Console.WriteLine("Error: {0}", ex.ToString());
            }
            finally
            {
                if (con != null)
                    con.Close();
            }
        }

        public void getCheckBoxInfo()
        {
            try
            {
                con.Open();
                SqlCommand cmd = new SqlCommand("select C.introBeforeEvaluationID, C.name, C.ssn, C.mobile, C.addres, C.gender, C.BirthYear, C.other from checkBoxInfo C where groupsID=" + globalGroupsID + " and evaluationID=" + globalEvaluationID, con);

                r = cmd.ExecuteReader();
                while (r.Read())
                {
                    chkIntroEvaluation.Checked = r.GetBoolean(0);
                    chkName.Checked = r.GetBoolean(1);
                    chkSsn.Checked = r.GetBoolean(2);
                    chkMobile.Checked = r.GetBoolean(3);
                    chkAddress.Checked = r.GetBoolean(4);
                    chkGender.Checked = r.GetBoolean(5);
                    chkBirthYear.Checked = r.GetBoolean(6);
                    chkOther.Checked = r.GetBoolean(7);
                    if (chkName.Checked || chkSsn.Checked || chkMobile.Checked || chkAddress.Checked || chkGender.Checked || chkBirthYear.Checked || chkOther.Checked)
                        chkInfoUserBefore.Checked = true;

                }
            }
            catch (SqlException ex)
            {
                Console.WriteLine("Error: {0}", ex.ToString());

            }
            finally
            {
                if (con != null)
                {
                    con.Close();
                }
            }
        }

        public void updateCheckBoxInfo()
        {
            try
            {
                con.Open();
                SqlCommand cmd = new SqlCommand("UPDATE checkBoxInfo set introBeforeEvaluationID=@introBf, name=@name, ssn=@ssn, mobile=@mobile, addres=@addres, gender=@gender, birthYear=@birthYear, other=@other, userFeedback=@userFeedBack where groupsID=@groupsID and evaluationID=@evaluationID ", con);
                cmd.Parameters.AddWithValue("@introBf", chkIntroEvaluation.Checked);
                cmd.Parameters.AddWithValue("@name", chkName.Checked);
                cmd.Parameters.AddWithValue("@ssn", chkSsn.Checked);
                cmd.Parameters.AddWithValue("@mobile", chkMobile.Checked);
                cmd.Parameters.AddWithValue("@addres", chkAddress.Checked);
                cmd.Parameters.AddWithValue("@gender", chkGender.Checked);
                cmd.Parameters.AddWithValue("@birthYear", chkBirthYear.Checked);
                cmd.Parameters.AddWithValue("@other", chkOther.Checked);
                cmd.Parameters.AddWithValue("@userFeedBack", chkInfoUserAfter.Checked);
                cmd.Parameters.AddWithValue("@groupsID", globalGroupsID);
                cmd.Parameters.AddWithValue("@evaluationID", globalEvaluationID);
                cmd.ExecuteNonQuery();

            }
            catch (SqlException ex)
            {
                Console.WriteLine("Error: {0}", ex.ToString());

            }
            finally
            {
                if (con != null)
                {
                    con.Close();
                }
            }
        }
        #endregion

        #region Events
        private void chkIntroEvaluation_CheckedChanged(object sender, EventArgs e)
        {
            if (chkIntroEvaluation.Checked)
            {
                btnFinish.Hide();
                btnNext.Show();
            }
            else
            {
                btnFinish.Show();
                btnNext.Hide();
            }
        }

        private void radEssay_CheckedChanged(object sender, EventArgs e)
        {
            if (chkInfoUserAfter.CheckState == CheckState.Checked || chkIntroEvaluation.CheckState == CheckState.Checked)
            {
                if (radEssay.Checked)
                {
                    this.pictureBox1.Show();
                    pictureBox1.Load("PreviewCreateEssay.PNG");
                    btnNext.Show();
                    btnFinish.Hide();
                }
                else
                {
                    this.pictureBox1.Hide();
                    btnNext.Hide();
                    btnFinish.Show();
                }
            }
        }

        private void radSurvey_CheckedChanged(object sender, EventArgs e)
        {
            if (chkInfoUserAfter.CheckState == CheckState.Checked || chkIntroEvaluation.CheckState == CheckState.Checked)
            {
                if (radSurvey.Checked)
                {
                    this.pictureBox1.Show();
                    pictureBox1.Load("PreviewCreateSurvey.PNG");
                    btnNext.Show();
                    btnFinish.Hide();
                }
                else
                {
                    this.pictureBox1.Hide();
                    btnNext.Hide();
                    btnFinish.Show();
                }
            }
        }

        private void chkEmail_CheckedChanged(object sender, EventArgs e)
        {
            if (chkEmail.CheckState == CheckState.Checked)
            {
                txtEmail.Enabled = true;
                this.pictureBox1.Show();
                pictureBox1.Load("PreviewEmailAddress.PNG");
            }
            else
            {
                txtEmail.Enabled = false;
                this.pictureBox1.Hide();
            }
        }

        private void chkInfoUserBefore_CheckedChanged(object sender, EventArgs e)
        {
            if (chkInfoUserBefore.CheckState == CheckState.Checked)
            {
                chkName.Enabled = true;
                chkSsn.Enabled = true;
                chkMobile.Enabled = true;
                chkAddress.Enabled = true;
                chkGender.Enabled = true;
                chkBirthYear.Enabled = true;
                chkOther.Enabled = true;
                this.pictureBox1.Show();
                pictureBox1.Load("PreviewInformationBefore.PNG");
            }
            else
            {
                chkName.Enabled = false;
                chkSsn.Enabled = false;
                chkMobile.Enabled = false;
                chkAddress.Enabled = false;
                chkGender.Enabled = false;
                chkBirthYear.Enabled = false;
                chkOther.Enabled = false;
                pictureBox1.Hide();
            }
        }
        #endregion

        #region OpenForms
        public static void OpenEditTask()
        {
            Application.Run(new EditTask());
        }
        public void OpenTesterInterface()
        {
            Application.Run(new TesterInterface());
        }
        public void OpenEditInroductionText()
        {
            Application.Run(new EditIntroductionText());
        }
        public static void OpenListOfProjects()
        {
            Application.Run(new ListOfProjects());
        }
        #endregion




    }

}
